package com.sychip.fhc.base

import android.app.Application
import androidx.lifecycle.viewModelScope
import com.fhc.view.FhcAppViewModel
import com.sychip.fhc.AppType
import com.sychip.fhc.app.pref.PrefDataStoreIf
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject


@HiltViewModel
open class BaseAppViewModel @Inject constructor(
    app: Application,
    private val prefDataStore: PrefDataStoreIf? = null,
    private val exceptionHandler: CoroutineExceptionHandler? = null
) : FhcAppViewModel(app) {
    protected fun viewModelLaunch(block: suspend CoroutineScope.() -> Unit) {
        if(exceptionHandler!= null){
            viewModelScope.launch(exceptionHandler) {
                block(this)
            }
        }else{
            viewModelScope.launch {
                block(this)
            }
        }
    }

    protected  val _uiCommonState:MutableStateFlow<ViewModelStates> = MutableStateFlow(initUICommonState())
    protected val uiCommonState:StateFlow<ViewModelStates> = _uiCommonState.asStateFlow()


    protected  val _appTypeState:MutableStateFlow<AppType> = MutableStateFlow(AppType.WSN)
    val appTypeState:StateFlow<AppType> = _appTypeState.asStateFlow()

    protected open fun initUICommonState():ViewModelStates{
        return ViewModelStates.Loading
    }

    protected var usbId: String = ""

    private var remindIfNotTablet: Boolean = true

    override fun  init()  {
        super.init()
        viewModelScope.launch {
            if (prefDataStore != null) {
                usbId = prefDataStore.getCurrentUsbId()
            }
        }
    }

    suspend fun getAppType(): AppType {
        var appType = AppType.WSN
        if(prefDataStore != null) {
            appType = prefDataStore.getAppType()
        }

        Timber.i("getAppType 111111111111111      >>>>>>>>>>>>>>>>>>>>>>>>>${prefDataStore != null}   ${appType}")
        return appType
    }


    fun saveAppType(appType:AppType) = viewModelScope.launch {
        if(prefDataStore != null){
            Timber.i(">>>APP.TYPE  APP.TYPE     ${appType.toString()}")
            prefDataStore.saveAppType(appType)
            Timber.i("getAppType 222222222222222  >>>>>>>>>>>>>>>>>>>>>>>>> ${getAppType()}")
        }
    }

    suspend fun remindNotTablet() : Boolean {
        var remind = true
        if(prefDataStore != null) {
            remind = prefDataStore.getRemindNotTablet()
        }
        Timber.i("remindIfNotTablet  >>>>>>>>>>  ${prefDataStore != null}   $remind")
        return remind
    }

    fun setRemindNotTablet(remind: Boolean = false) {
        viewModelScope.launch {
            prefDataStore?.setRemindNotTablet(remind)
        }
    }
//
//    protected var client: ClientBleGatt? = null
//    protected lateinit var ledCharacteristic: ClientBleGattCharacteristic
//    protected lateinit var videoCharacteristic: ClientBleGattCharacteristic
//
//    open fun connect(bleScanResults: BleScanResults) = viewModelScope.launch {
//        val bleDevice: ServerDevice = bleScanResults.device
//        Timber.i("connect  >>>>>>>>>>>>>>>>>>>>>>>>> ${bleDevice.name}      $context")
//        //Connect a Bluetooth LE device.
//        val a = ActivityCompat.checkSelfPermission(this@BaseAppViewModel.context, Manifest.permission.BLUETOOTH_CONNECT)
//        if (ActivityCompat.checkSelfPermission(this@BaseAppViewModel.context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED){
//
//            val client = ClientBleGatt.connect(context, bleDevice, viewModelScope).also {
//                this@BaseAppViewModel.client = it
//            }
//
//            Timber.i("isConnected  >>>>>>>>>>>>>>>>>>>>>>>>> ${client.isConnected}")
//            if (client.isConnected) {
//                val services = client.discoverServices()
//                services.services.forEach {it->
//                    Timber.i("discoverServices  >>>>>>>>>>>>>>>>>>>>>>>>> ${it.uuid}")
//                }
//                configureGatt(services)
//            }
//
//        }else{
//            Timber.i("checkSelfPermission  >>>>>>>>>>>>>>>>>>>>>>>>> ${a} ${PackageManager.PERMISSION_GRANTED} ")
//        }
//
//    }

    //    private fun isMacAddress(address: String): Boolean {
//        val macPattern = "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$"
//        val regex = Regex(macPattern)
//        return regex.matches(address)
//    }
//    open fun connect(mac: String,name: String) = viewModelScope.launch {
//        if(!isMacAddress(mac)){
//            this@BaseAppViewModel.updateBleNFCConnected(-1)
//            return@launch
//        }
//        Timber.i("connect  >>>>>>>>>>>>>>>>>>>>>>>>> ${name}      $mac")
//        //Connect a Bluetooth LE device.
//        val a = ActivityCompat.checkSelfPermission(this@BaseAppViewModel.context, Manifest.permission.BLUETOOTH_CONNECT)
//        if (ActivityCompat.checkSelfPermission(this@BaseAppViewModel.context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED){
//
//            this@BaseAppViewModel.updateBleNFCConnected(1, mac)
//            val client = ClientBleGatt.connect(context, mac, viewModelScope, ).also {
//                this@BaseAppViewModel.client = it
//            }
//
//            Timber.i("isConnected  >>>>>>>>>>>>>>>>>>>>>>>>> ${client.isConnected}")
//            if (client.isConnected) {
//                val services = client.discoverServices()
//                services.services.forEach {it->
//                    Timber.i("discoverServices  >>>>>>>>>>>>>>>>>>>>>>>>> ${it.uuid}")
//                }
//                this@BaseAppViewModel.updateBleNFCConnected(2)
//                configureGatt(services)
//            }else{
//                this@BaseAppViewModel.updateBleNFCConnected(-1)
//            }
//
//        }else{
//
//            Timber.i("checkSelfPermission  >>>>>>>>>>>>>>>>>>>>>>>>> ${a} ${PackageManager.PERMISSION_GRANTED} ")
//        }
//
//    }
//
//    private suspend fun configureGatt(services: ClientBleGattServices) {
//        //Remember needed service and characteristics which are used to communicate with the DK.
//        val service = services.findService(BleUuids.UUID_SERVICE_DEVICE)
//        if(service != null){
//            service.characteristics.forEach {it->
//                Timber.i("characteristics  >>>>>>>>>>>>>>>>>>>>>>>>> ${it.uuid}")
//            }
//            ledCharacteristic = service.findCharacteristic(BleUuids.UUID_WRITE_CHAR)!!
//            videoCharacteristic = service.findCharacteristic(BleUuids.UUID_VIDEO_CHAR)!!
//
//            //Observe button characteristic which detects when a button is pressed
//            videoCharacteristic.getNotifications().onEach {
////            _state.value = _state.value.copy(isButtonPressed = BlinkyButtonParser.isButtonPressed(it))
//            }.launchIn(viewModelScope)
//        }else{
//
//        }
//
//    }
    override fun onCleared() {
        // 清理资源
    }
}